package DAL;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {
	
    private static final char[] hexadecimal =
    {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
     'a', 'b', 'c', 'd', 'e', 'f'};
	
	public String decode(String value) {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
	        md.update(value.getBytes("UTF-8"));
	        byte[] byteValues = md.digest();
	        byte singleChar = 0;
	        if (byteValues == null || byteValues.length <= 0) return null;
	 
	        StringBuffer out = new StringBuffer(byteValues.length * 2);
	 
	        for (int i = 0; i < byteValues.length; i++) {
	            singleChar = (byte) (byteValues[i] & 0xF0);
	            singleChar = (byte) (singleChar >>> 4);
	            singleChar = (byte) (singleChar & 0x0F);
	            out.append(hexadecimal[(int) singleChar]); 
	            singleChar = (byte) (byteValues[i] & 0x0F); 
	            out.append(hexadecimal[(int) singleChar]);
	        }
	        String rslt = new String(out);
	        return rslt;
		}
		catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; }
		catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; }
    }
	
    public String encode( byte[] binaryData ) {

        if (binaryData.length != 16)
            return null;

        char[] buffer = new char[32];

        for (int i=0; i<16; i++) {
            int low = (int) (binaryData[i] & 0x0f);
            int high = (int) ((binaryData[i] & 0xf0) >> 4);
            buffer[i*2] = hexadecimal[high];
            buffer[i*2 + 1] = hexadecimal[low];
        }

        return new String(buffer);
    }
}
